import { Body, Controller, Post } from '@midwayjs/core';
import { RespInfo, RespStatusCode } from '../types/common.type';
import { RespMethod } from '../util/common.method';
const http = require('http')
const https = require('https')


@Controller('/common')
export class CommonController {

  /** 校验链接可访问性 */
  @Post('/reghref')
  async regHref(@Body() info: { href: string }): Promise<RespInfo> {
    const { href } = info;
    return new Promise(reslove => {
      try {
        let httpC = href.includes('https') ? https : http;
        const request = httpC.get(href, response => {
          if (response.statusCode == 200) {
            reslove(RespMethod())
          } else {
            reslove(RespMethod({}, RespStatusCode.Error, '链接无法访问'))
          }
        })
        request.on('error', error => {
          reslove(RespMethod({}, RespStatusCode.Error, '链接无法访问'))
        })
      } catch (error) {
        reslove(RespMethod({}, RespStatusCode.Error, '链接无法访问'))
      }
    })
  }

}
